#include "musicslider.h"
#include "ui_musicslider.h"
#include<QDebug>
MusicSlider::MusicSlider(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::MusicSlider)
{
    ui->setupUi(this);
    currentPos = 0;
    maxWidth = width();
    qDebug()<<maxWidth;
    moveSilder();
}

MusicSlider::~MusicSlider()
{
    delete ui;
}

void MusicSlider::mousePressEvent(QMouseEvent *event)
{
    // 注意：QMouseEvent中的pos()为⿏标相对于widget的坐标，不是相当于screen
    // 因此⿏标位置的 x 坐标可直接作为outLine的宽度
    currentPos = event->pos().x();
    moveSilder();
}

void MusicSlider::mouseMoveEvent(QMouseEvent *event)
{
    QRect rect = QRect(0, 0, width(), height());
    QPoint pos = event->pos();
    if(!rect.contains(pos))
    {
        return;
    }
    // 根据⿏标滑动的位置更新outLine的宽度
    if(event->buttons() == Qt::LeftButton)
    {
    // 验证：⿏标点击的x坐标是否越界，如果越界将其调整到边界
        currentPos = event->pos().x();
        if(currentPos < 0)
        {
            currentPos = 0;
        }
        if(currentPos > maxWidth)
        {
            currentPos = maxWidth;
        }
        moveSilder();
    }
}

void MusicSlider::mouseReleaseEvent(QMouseEvent *event)
{
    currentPos = event->pos().x();
    moveSilder();
    emit setMusicSliderPosition((float)currentPos / (float)maxWidth);
}

void MusicSlider::moveSilder()
{
    // 根据当前进度设置外部滑动条的位置
    ui->outLine->setMaximumWidth(currentPos);
    ui->outLine->setGeometry(0,8, currentPos, 4);
}

void MusicSlider::setStep(float bf)
{
    currentPos = maxWidth*bf;
    moveSilder();
}
